<template>
  <div class="dashboard">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>数据仪表盘</h1>
      <p>实时监控考试系统运行状态</p>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon students">
          <i class="fas fa-users"></i>
        </div>
        <div class="stat-content">
          <h3>{{ dashboardData.totalGroups }}</h3>
          <p>总分组数</p>
          <span class="stat-change positive">+{{ dashboardData.newGroups }} 本月新增</span>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon exams">
          <i class="fas fa-file-alt"></i>
        </div>
        <div class="stat-content">
          <h3>{{ dashboardData.totalExams }}</h3>
          <p>总考试数</p>
          <span class="stat-change positive">+{{ dashboardData.newExams }} 本月新增</span>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon questions">
          <i class="fas fa-question-circle"></i>
        </div>
        <div class="stat-content">
          <h3>{{ dashboardData.totalQuestions }}</h3>
          <p>题库总数</p>
          <span class="stat-change positive">+{{ dashboardData.newQuestions }} 本月新增</span>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon submissions">
          <i class="fas fa-clipboard-check"></i>
        </div>
        <div class="stat-content">
          <h3>{{ dashboardData.totalSubmissions }}</h3>
          <p>总提交数</p>
          <span class="stat-change neutral">{{ dashboardData.pendingGrading }} 待批改</span>
        </div>
      </div>
    </div>
    
    <!-- 图表区域 -->
    <div class="charts-grid">
      <!-- 考试趋势图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>考试趋势</h3>
          <el-select v-model="examTrendPeriod" size="small">
            <el-option label="最近7天" value="7d" />
            <el-option label="最近30天" value="30d" />
            <el-option label="最近3个月" value="3m" />
          </el-select>
        </div>
        <div ref="examTrendChart" class="chart-container"></div>
      </div>
      
      <!-- 成绩分布图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>成绩分布</h3>
          <el-select v-model="scoreDistributionExam" size="small">
            <el-option 
              v-for="exam in recentExams" 
              :key="exam.id" 
              :label="exam.name" 
              :value="exam.id" 
            />
          </el-select>
        </div>
        <div ref="scoreDistributionChart" class="chart-container"></div>
      </div>
    </div>
    
    <!-- 活动列表 -->
    <div class="activity-section">
      <div class="activity-header">
        <h3>最近活动</h3>
        <el-button type="primary" link @click="viewAllActivities">
          查看全部
        </el-button>
      </div>
      
      <div class="activity-list">
        <div 
          v-for="activity in recentActivities" 
          :key="activity.id" 
          class="activity-item"
        >
          <div class="activity-icon">
            <i :class="activity.icon"></i>
          </div>
          <div class="activity-content">
            <h4>{{ activity.title }}</h4>
            <p>{{ activity.description }}</p>
            <span class="activity-time">{{ activity.time }}</span>
          </div>
          <div class="activity-action">
            <el-button 
              v-if="activity.actionText" 
              size="small" 
              type="primary" 
              link
              @click="handleActivityAction(activity)"
            >
              {{ activity.actionText }}
            </el-button>
          </div>
        </div>
      </div>
    </div>
    

  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getDashboardData, getGroupList } from '@/api/rbac/admin'
import { listMyQuestions } from '@/api/questions/questions'
import { getMyExamsList } from '@/api/exam/exams'
import { getMyExamAssignments } from '@/api/exam/examAssignments'
import { useAppStore } from '@/stores'

const router = useRouter()
const appStore = useAppStore()

const examTrendChart = ref(null)
const scoreDistributionChart = ref(null)
const examTrendPeriod = ref('7d')
const scoreDistributionExam = ref(1)
const loading = ref(false)

const dashboardData = ref({
  totalGroups: 0,
  newGroups: 0,
  totalExams: 0,
  newExams: 0,
  totalQuestions: 0,
  newQuestions: 0,
  totalSubmissions: 0,
  pendingGrading: 0
})

const recentExams = ref([])

const recentActivities = ref([])

const initExamTrendChart = () => {
  const chart = echarts.init(examTrendChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['考试数量', '参与人数']
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: [
      {
        type: 'value',
        name: '考试数量',
        position: 'left'
      },
      {
        type: 'value',
        name: '参与人数',
        position: 'right'
      }
    ],
    series: [
      {
        name: '考试数量',
        type: 'bar',
        data: [],
        itemStyle: {
          color: '#165dff'
        }
      },
      {
        name: '参与人数',
        type: 'line',
        yAxisIndex: 1,
        data: [],
        itemStyle: {
          color: '#00d4aa'
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const initScoreDistributionChart = () => {
  const chart = echarts.init(scoreDistributionChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['优秀(90-100)', '良好(80-89)', '中等(70-79)', '及格(60-69)', '不及格(0-59)']
    },
    series: [
      {
        name: '成绩分布',
        type: 'pie',
        radius: '50%',
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const loadDashboardData = async () => {
  try {
    loading.value = true
    appStore.setLoading(true)
    
    // 并行获取各种数据
    const [groupsResponse, questionsResponse, examsResponse, assignmentsResponse] = await Promise.allSettled([
      getGroupList(),
      listMyQuestions(),
      getMyExamsList(),
      getMyExamAssignments()
    ])
    
    // 处理分组数据
    let totalGroups = 0
    if (groupsResponse.status === 'fulfilled' && groupsResponse.value?.data) {
      totalGroups = Array.isArray(groupsResponse.value.data) ? groupsResponse.value.data.length : 0
    }
    
    // 处理题目数据
    let totalQuestions = 0
    if (questionsResponse.status === 'fulfilled' && questionsResponse.value?.data) {
      totalQuestions = Array.isArray(questionsResponse.value.data) ? questionsResponse.value.data.length : 0
    }
    
    // 处理试卷数据
    let totalExams = 0
    if (examsResponse.status === 'fulfilled' && examsResponse.value?.data) {
      totalExams = Array.isArray(examsResponse.value.data) ? examsResponse.value.data.length : 0
    }
    
    // 处理考试安排数据
    let totalSubmissions = 0
    if (assignmentsResponse.status === 'fulfilled' && assignmentsResponse.value?.data) {
      totalSubmissions = Array.isArray(assignmentsResponse.value.data) ? assignmentsResponse.value.data.length : 0
    }
    
    // 更新仪表盘数据
    dashboardData.value = {
      totalGroups,
      newGroups: 0, // 暂时设为0，需要后端支持
      totalExams,
      newExams: 0, // 暂时设为0，需要后端支持
      totalQuestions,
      newQuestions: 0, // 暂时设为0，需要后端支持
      totalSubmissions,
      pendingGrading: 0 // 暂时设为0，需要后端支持
    }
    
    // 模拟最近考试列表
    recentExams.value = [
      { id: 1, name: '数据结构期末考试' },
      { id: 2, name: '算法设计测验' },
      { id: 3, name: '计算机网络作业' }
    ]
    
    // 模拟最近活动
    recentActivities.value = [
      {
        id: 1,
        title: '新学生注册',
        description: '3名新学生完成注册',
        time: '2小时前',
        icon: 'fas fa-user-plus',
        actionText: '查看详情'
      },
      {
        id: 2,
        title: '考试提交',
        description: '数据结构考试有新的提交',
        time: '4小时前',
        icon: 'fas fa-file-upload',
        actionText: '去批改'
      },
      {
        id: 3,
        title: '异常检测',
        description: '检测到可疑的考试行为',
        time: '6小时前',
        icon: 'fas fa-exclamation-triangle',
        actionText: '查看报告'
      },
      {
        id: 4,
        title: '题目更新',
        description: '算法题库新增10道题目',
        time: '1天前',
        icon: 'fas fa-plus-circle',
        actionText: '查看题目'
      }
    ]
    
  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
    ElMessage.error('加载数据失败，请稍后重试')
  } finally {
    loading.value = false
    appStore.setLoading(false)
  }
}

const viewAllActivities = () => {
  // 跳转到活动列表页面
}

const handleActivityAction = (activity) => {
  switch (activity.id) {
    case 1:
      router.push('/admin/students')
      break
    case 2:
      router.push('/admin/grading')
      break
    case 3:
      router.push('/admin/anticheat')
      break
    case 4:
      router.push('/admin/questions')
      break
  }
}

onMounted(async () => {
  await loadDashboardData()
  await nextTick()
  initExamTrendChart()
  initScoreDistributionChart()
})
</script>

<style lang="scss" scoped>
.dashboard {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 32px;
  
  h1 {
    font-size: 28px;
    font-weight: 700;
    color: var(--neutral-700);
    margin-bottom: 8px;
  }
  
  p {
    color: var(--neutral-500);
    font-size: 16px;
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  }
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  
  i {
    font-size: 24px;
    color: white;
  }
  
  &.students {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }
  
  &.exams {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  }
  
  &.questions {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  }
  
  &.submissions {
    background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  }
}

.stat-content {
  flex: 1;
  
  h3 {
    font-size: 32px;
    font-weight: 700;
    color: var(--neutral-700);
    margin-bottom: 4px;
  }
  
  p {
    color: var(--neutral-500);
    font-size: 14px;
    margin-bottom: 8px;
  }
  
  .stat-change {
    font-size: 12px;
    font-weight: 500;
    
    &.positive {
      color: var(--success-color);
    }
    
    &.negative {
      color: var(--error-color);
    }
    
    &.neutral {
      color: var(--warning-color);
    }
  }
}

.charts-grid {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
  margin-bottom: 32px;
  
  @media (max-width: 1024px) {
    grid-template-columns: 1fr;
  }
}

.chart-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h3 {
    font-size: 18px;
    font-weight: 600;
    color: var(--neutral-700);
  }
}

.chart-container {
  height: 300px;
}

.activity-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 32px;
}

.activity-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h3 {
    font-size: 18px;
    font-weight: 600;
    color: var(--neutral-700);
  }
}

.activity-list {
  .activity-item {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 16px 0;
    border-bottom: 1px solid var(--neutral-200);
    
    &:last-child {
      border-bottom: none;
    }
    
    .activity-icon {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background: rgba(22, 93, 255, 0.1);
      display: flex;
      align-items: center;
      justify-content: center;
      
      i {
        color: var(--primary-color);
      }
    }
    
    .activity-content {
      flex: 1;
      
      h4 {
        font-size: 14px;
        font-weight: 600;
        margin-bottom: 4px;
        color: var(--neutral-700);
      }
      
      p {
        font-size: 13px;
        color: var(--neutral-500);
        margin-bottom: 4px;
      }
      
      .activity-time {
        font-size: 12px;
        color: var(--neutral-400);
      }
    }
  }
}

.quick-actions {
  h3 {
    font-size: 18px;
    font-weight: 600;
    color: var(--neutral-700);
    margin-bottom: 20px;
  }
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.action-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
    
    i {
      color: var(--primary-color);
    }
  }
  
  i {
    font-size: 32px;
    color: var(--neutral-400);
    transition: color 0.3s ease;
  }
  
  span {
    font-weight: 500;
    color: var(--neutral-600);
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .charts-grid {
    grid-template-columns: 1fr;
  }
  
  .actions-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>